package com.sline.com.sline.Synchronized;

public class Demo1_Synchronized {
    public static void main(String[] args) {
        // demo1();

        Printer p1 = new Printer();
        new Thread() {
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    p1.print5();
                }
            }
        }.start();
        new Thread() {
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    p1.print6();
                }
            }
        }.start();
    }

    private static void demo1() {
        Printer p1 = new Printer();
        new Thread() {
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    p1.print1();
                }
            }
        }.start();
        new Thread() {
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    p1.print2();
                }
            }
        }.start();
    }
}

class Printer {
    public void print1() {
        synchronized("a") {             // 同步代码块, 锁机制
            System.out.print("黑");
            System.out.print("马");
            System.out.print("程");
            System.out.print("序");
            System.out.print("员");
            System.out.println("");
        }
    }
    public void print2() {
        synchronized("a") {
            System.out.print("传");
            System.out.print("智");
            System.out.print("播");
            System.out.print("客");
            System.out.println("");
        }
    }

    // 非静态的同步方法的锁对象是this
    public synchronized void print3() {
        System.out.print("我");
        System.out.print("是");
        System.out.print("黑");
        System.out.print("马");
        System.out.print("程");
        System.out.print("序");
        System.out.print("员");
        System.out.println("");
    }
    public void print4() {
        synchronized(this) {
            System.out.print("这");
            System.out.print("里");
            System.out.print("是");
            System.out.print("传");
            System.out.print("智");
            System.out.print("播");
            System.out.print("客");
            System.out.println("");
        }
    }

    // 静态的同步方法的锁对象是类的字节码对象
    public static synchronized void print5() {
        System.out.print("黑");
        System.out.print("马");
        System.out.print("程");
        System.out.print("序");
        System.out.print("员");
        System.out.println(" ");
    }
    public void print6() {
        synchronized(Printer.class) {
            System.out.print("传");
            System.out.print("智");
            System.out.print("播");
            System.out.print("客");
            System.out.println(" ");
        }
    }
}